﻿var app = angular.module("starter");

app.factory('sky.lyjt.patroService', [
     "$q",
     "$rootScope",
     "$http",
     "$cordovaFileTransfer",
     "baseurl",
    function ($q, $rootScope, $http,$cordovaFileTransfer, baseurl) {
        var saveUrl = baseurl + "api/services/app/patrolInfo/SavePatroInfo";

        var uploadFile = baseurl + "api/FileUpload";

        /**/
        var saveImage = function (images, patrol) {
            var self = this;
            var uploadPromise = [];
            _.forEach(images, function (item) {
                var promise = self.upload(item);
                uploadPromise.push(promise);
            });

            var allPromise = $q.all(uploadPromise);

            return allPromise.then(function (res) {

                var datas = _.map(res, function(item) {
                    return JSON.parse(item.response);
                });

                patrol.files = _.map(datas, function (item) {
                    return item.result;
                });

                return $http({
                    method: "POST",
                    url: saveUrl,
                    data: JSON.stringify(patrol),
                    headers: {
                        'Authorization': 'Bearer ' + $rootScope.app.userKey
                    }
                });
            });

/*
            var formData = new FormData();

            _.forEach(images, function (item) {
                formData.append("files", item/*, "images.jpg"#1#);
            });

            formData.append("Desc", 1);
            formData.append("Lng", "0");
            formData.append("Lat", "0");
            formData.append("PatrolType", "1");
            formData.append("InspectionDate", moment(datetime).format("YYYY-MM-DD HH:mm:ss"));

            */
        };

        var upload= function(url) {

            var fileUploadOptions = new FileUploadOptions();
            fileUploadOptions.fileKey="file";
            
            fileUploadOptions.mimeType="image/jpeg";

            return $cordovaFileTransfer.upload(uploadFile, url, fileUploadOptions);
        }

        return {
            saveImage: saveImage,
            upload: upload
        };

    }]);